/**
 * 用于生成slidbar

 * Created by Administrator on 2016/1/27.
 */

(function ($) {
    "use strict";
    moment.locale("zh-cn");
    var mainContent = $("#page-content");
    var selectId, table, selectRow, detailTable, lastLoadFxid,hzdsc=false;

    /**
     * 初始化表格
     */
    function aceSwitch(cellvalue, options, cell) {
        setTimeout(function () {
            $(cell).find('input[type=checkbox]')
                .addClass('ace ace-switch ace-switch-5')
                .after('<span class="lbl"></span>');
        }, 0);
    }

    function updatePagerIcons(table) {
        var replacement =
        {
            'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
            'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
            'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
            'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
        };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

            if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
        })
    }

    function enableTooltips(table) {
        $('.navtable .ui-pg-button').tooltip({container: 'body'});
        $(table).find('.ui-pg-div').tooltip({container: 'body'});
    }

    /**
     * 初始化日期选择控件
     */
    var initDatepicker = function () {
        $('.date-picker').datepicker({
                autoclose: true,
                language: 'zh-CN',
                todayHighlight: true
            })
            //show datepicker when clicking on the icon
            .next().on(ace.click_event, function () {
            $(this).prev().focus();
        });
    };
    /**
     * 初始化附件上传
     */
    var initUploader = function () {
        var $this = $(".upload-select");
        $this.fileupload({
            url: $.router.server + 'encl/uploadHZ',
            dataType: 'json',
            done: function (e, data) {
                var rs = data.result;
                if (rs.success) {
                    hzdsc = true;
                    $("#hzd_name").html(data.originalFiles[0].name);
                    alert("文件:" + data.originalFiles[0].name + "上传成功!");
                } else {
                    alert("文件:" + data.originalFiles[0].name + "上传失败!" + rs.message);
                }
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
        $this.bind('fileuploadsubmit', function (e, data) {
            // The example input, doesn't have to be part of the upload form:
            data.formData = {
                'rpid': selectRow["id"],
                'hcsj': selectRow["hcsj"]
            };
            if (!data.formData.hcsj) {
                data.context.find('button').prop('disabled', false);
                $("#st2_hcsj").focus();
                return false;
            }
        });
    };

    /**
     * 读取风险详情
     * @param id
     */
    var loadInfo = function (id) {
        $.request(
            $.router.server + "repm/find",
            {
                "type": "post",
                "data": {
                    replyId: id
                },
                "callback": function (data) {
                    for (var i in data) {
                        var d = data[i];
                        for (var j in d) {
                            $("#st2_" + j).val(d[j])
                        }
                    }
                    //$("#st2_filename").html(data[2]["filename"]);
                    //$("#st2_filename").attr("href", $.router.server+"encl/download?id=" + data[2]["id"]);
                    $("#hzd_name").html("");
                    $("#st2_hcsj").val(moment($("#st2_hcsj").val(), "mm-dd-yyyy").format("YYYY-MM"));
                }
            }
        )
    };

    /**
     * 初始化风险详单表格
     */
    var initDetailGrid = function () {
        //var boot = $("#bootHtml");
        var grid_selector = "#detail-table",
            pager_selector = "#detail-pager";

        // 风险没有变化,不需要重新初始化表格
        //if(lastLoadFxid==selectRow["fxid"]){
        //    detailTable.trigger("reloadGrid");
        //    return
        //}
        //lastLoadFxid = selectRow["fxid"];
        // 每种风险表格不同,清理现场
        //$(grid_selector).jqGrid('GridDestroy','detail-table');
        //$(boot).empty();
        //$(boot).append('<table id="detail-table"></table>');
        //$(boot).append('<div id="detail-pager"></div>');

        // 获取风险结构
        $.request(
            $.router.server + "repm/get_risk",
            {
                "type": "post",
                "data": {
                    fxid: selectRow["fxid"]
                },
                "callback": function (data) {
                    if (data.success == false) {
                        bootbox.dialog({
                            message: data.message,
                            buttons: {
                                "success": {
                                    "label": "确定",
                                    "className": "btn-sm btn-primary"
                                }
                            }
                        });
                        return;
                    }
                    var columns = data["columns"],
                        colNames = [],
                        colModel = [];
                    for (var i in columns) {
                        if(!columns.hasOwnProperty(i)){
                            continue;
                        }
                        colNames.push(columns[i]["name"]);
                        colModel.push({
                            "name": columns[i]["id"]
                        })
                    }

                    $(window).on('resize.jqGrid', function () {
                        $(grid_selector).jqGrid('setGridWidth', $("#step-container").width());
                    });
                    //resize on sidebar collapse/expand
                    var parent_column = $(grid_selector).closest('[class*="col-"]');
                    $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
                        if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                            $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                        }
                    });
                    $(grid_selector).jqGrid({
                        //datatype: "xml",
                        //for this example we are using local data
                        url: $.router.server + "repm/detail_risk",
                        mtype: "POST",
                        postData: {
                            "fxid": selectRow["fxid"],
                            "cycle": selectRow["hcsj"]
                        },
                        datatype: "json",
                        height: 400,
                        colNames: colNames,
                        colModel: colModel,
                        repeatitems: false,
                        jsonReader: {
                            root: "datas",    // json中代表实际模型数据的入口
                            page: "page",    // json中代表当前页码的数据
                            total: "pageCount",    // json中代表页码总数的数据
                            records: "total" // json中代表数据行总数的数据
                        },
                        viewrecords: true,
                        rowNum: 10,
                        //rowList: [10, 20, 30],
                        pager: pager_selector,
                        altRows: true,
                        //toppager: true,

                        multiselect: false,
                        //multikey: "ctrlKey",
                        multiboxonly: false,

                        loadComplete: function () {
                            var table = this;
                            setTimeout(function () {
                                //styleCheckbox(table);
                                //
                                //updateActionIcons(table);
                                updatePagerIcons(table);
                                enableTooltips(table);
                            }, 0);
                        },
                        autowidth: true
                    });
                    detailTable = $(grid_selector);
                    $(window).triggerHandler('resize.jqGrid');
                }
            }
        );
    };
    /**
     * 初始化风险列表
     */
    var initGrid = function () {
        selectId = null;
        selectRow = null;
        var grid_selector = "#grid-table";
        var pager_selector = "#grid-pager";
        $(window).on('resize.jqGrid', function () {
            $(grid_selector).jqGrid('setGridWidth', $("#step-container").width());
        });
        //resize on sidebar collapse/expand
        var parent_column = $(grid_selector).closest('[class*="col-"]');
        $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
            if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                $(grid_selector).jqGrid('setGridWidth', parent_column.width());
            }
        });
        $(grid_selector).jqGrid({
            //datatype: "xml",
            //for this example we are using local data
            url: $.router.server + "repm/page",
            mtype: "POST",
            postData: {
                "reply.hcsj": moment().startOf('month').format("L"),
                "reply.status":0
            },
            datatype: "json",
            height: 180,
            colNames: [' ', '风险ID', '风险名称', '核查时间', '反馈时间'],
            colModel: [
                {
                    name: 'id', index: '', width: 80, fixed: true, sortable: false, resize: false,
                    hidden: true
                },
                {
                    name: 'fxid',
                    width: 120,
                    editable: false
                },
                {
                    name: 'fxdmc',
                    width: 250,
                    editable: false
                },
                {
                    name: 'hcsj',
                    index: 'hcsj',
                    width: 120,
                    editable: false,
                    sorttype: "date",
                    formatter: function (data) {
                        var local = "zh-cn";
                        if($.checkStartChar(data)){
                            local="en";
                        }
                        moment.locale(local);
                        var rs = moment(data, "MMM dd YYYY").format("YYYY-MM");
                        moment.locale("zh-cn");
                        return rs;
                    }
                },
                {
                    name: 'fksj',
                    index: 'fksj',
                    width: 120,
                    editable: false,
                    sorttype: "date",
                    formatter: function (data) {
                        if (data) {
                            return moment(data).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return "";
                    }
                }
            ],
            repeatitems: false,
            jsonReader: {
                root: function (data) {
                    var datas = data["datas"];
                    var result = [];
                    for (var i in datas) {
                        if(!datas.hasOwnProperty(i)){
                            continue;
                        }
                        result.push({
                            "id": datas[i][0]["id"],
                            "fxid": datas[i][0]["fxid"],
                            "fxdmc": datas[i][1]["fxdmc"],
                            "hcsj": datas[i][0]["hcsj"],
                            "fksj": datas[i][0]["fksj"]
                        });
                    }
                    return result;
                },    // json中代表实际模型数据的入口
                page: "page",    // json中代表当前页码的数据
                total: "pageCount",    // json中代表页码总数的数据
                records: "total" // json中代表数据行总数的数据
            },
            viewrecords: true,
            rowNum: 10,
            //rowList: [10, 20, 30],
            pager: pager_selector,
            altRows: true,
            //toppager: true,

            multiselect: false,
            //multikey: "ctrlKey",
            multiboxonly: false,

            loadComplete: function () {
                var table = this;
                setTimeout(function () {
                    //styleCheckbox(table);
                    //
                    //updateActionIcons(table);
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            },
            onSelectRow: function (id) {
                selectId = id;
                selectRow = $(this).jqGrid('getRowData', id);
            }
            //,autowidth: true,
            /**
             ,
             grouping:true,
             groupingView : {
						 groupField : ['name'],
						 groupDataSorted : true,
						 plusicon : 'fa fa-chevron-down bigger-110',
						 minusicon : 'fa fa-chevron-up bigger-110'
					},
             caption: "Grouping"
             */
        });
        table = $(grid_selector);
        $(window).triggerHandler('resize.jqGrid');
    };
    var pageReady = function () {

        $('#fuelux-wizard')
            .ace_wizard({})
            .on('change', function (e, info) {
                if (!selectId) {
                    bootbox.dialog({
                        message: "请选中一行进行处理",
                        buttons: {
                            "success": {
                                "label": "关闭",
                                "className": "btn-sm btn-primary"
                            }
                        }
                    });
                    return false;
                }
                if (info.step == 1 && info.direction == "next") {
                    hzdsc = false;
                    $("#hzd_name").html("");
                    loadInfo(selectId);
                }
            })
            .on('changed', function (e) {
                // wizard changed fin.
            })
            .on('finished', function (e) {
                if (!hzdsc){
                    alert("必须上传回执单");
                    return false;
                }
                var validForm = $('#validation-form');
                if (!validForm.valid()) return false;
                var data = validForm.serializeArray();
                data.push({
                    "name":"sftghzd",
                    "value":hzdsc?1:0
                });
                data.push({
                    "name":"id",
                    "value":selectRow["id"]
                });
                hzdsc = false;
                $.request(
                    $.router.server + "repm/save",
                    {
                        "type": "post",
                        "data": data,
                        "callback": function (data) {
                            if (data.success) {
                                bootbox.dialog({
                                    message: "处理完成",
                                    buttons: {
                                        "success": {
                                            "label": "确定",
                                            "className": "btn-sm btn-primary",
                                            "callback": function () {
                                                table.trigger("reloadGrid");
                                                var wizard = $('#fuelux-wizard').data('wizard');
                                                wizard.currentStep = 1;
                                                wizard.setState();
                                            }
                                        }
                                    }
                                });
                            } else {
                                bootbox.dialog({
                                    message: data.message,
                                    buttons: {
                                        "success": {
                                            "label": "确定",
                                            "className": "btn-sm btn-primary"
                                        }
                                    }
                                });
                            }
                        }
                    }
                );
            }).on('stepclick', function (e) {
            //e.preventDefault();//this will prevent clicking and selecting steps
        });

        //jump to a step
        $('#step-jump').on('click', function () {
            var wizard = $('#fuelux-wizard').data('wizard');
            wizard.currentStep = 3;
            wizard.setState();
        });

        $.mask.definitions['~'] = '[+-]';

        $('#validation-form').validate({
            errorElement: 'div',
            errorClass: 'help-block',
            focusInvalid: false,
            rules: {
                email: {
                    required: true,
                    email: true
                },
                password: {
                    required: true,
                    minlength: 5
                },
                password2: {
                    required: true,
                    minlength: 5,
                    equalTo: "#password"
                },
                name: {
                    required: true
                },
                phone: {
                    required: true,
                    phone: 'required'
                },
                url: {
                    required: true,
                    url: true
                },
                comment: {
                    required: true
                },
                date: {
                    required: true,
                    date: true
                },
                state: {
                    required: true
                },
                platform: {
                    required: true
                },
                subscription: {
                    required: true
                },
                gender: 'required',
                agree: 'required'
            },

            messages: {
                required: "必选字段",
                remote: "请修正该字段",
                email: {
                    required: "Please provide a valid email.",
                    email: "Please provide a valid email."
                },
                password: {
                    required: "Please specify a password.",
                    minlength: "Please specify a secure password."
                },
                subscription: "Please choose at least one option",
                gender: "Please choose gender",
                agree: "Please accept our policy"
            },


            highlight: function (e) {
                $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
            },

            success: function (e) {
                $(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
                $(e).remove();
            },

            errorPlacement: function (error, element) {
                if (element.is(':checkbox') || element.is(':radio')) {
                    var controls = element.closest('div[class*="col-"]');
                    if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                    else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
                }
                else if (element.is('.select2')) {
                    error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
                }
                else if (element.is('.chosen-select')) {
                    error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
                }
                else error.insertAfter(element.parent());
            },

            submitHandler: function (form) {
            },
            invalidHandler: function (form) {
            }
        });
        jQuery.extend(jQuery.validator.messages, {
            required: "必选字段",
            remote: "请修正该字段",
            email: "请输入正确格式的电子邮件",
            url: "请输入合法的网址",
            date: "请输入合法的日期",
            dateISO: "请输入合法的日期 (ISO).",
            number: "请输入合法的数字",
            digits: "只能输入整数",
            creditcard: "请输入合法的信用卡号",
            equalTo: "请再次输入相同的值",
            accept: "请输入拥有合法后缀名的字符串",
            maxlength: jQuery.validator.format("请输入一个 长度最多是 {0} 的字符串"),
            minlength: jQuery.validator.format("请输入一个 长度最少是 {0} 的字符串"),
            rangelength: jQuery.validator.format("请输入 一个长度介于 {0} 和 {1} 之间的字符串"),
            range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),
            max: jQuery.validator.format("请输入一个最大为{0} 的值"),
            min: jQuery.validator.format("请输入一个最小为{0} 的值")
        });

        initGrid();
        initDatepicker();
        initUploader();
        /**
         $('#date').datepicker({autoclose:true}).on('changeDate', function(ev) {
					$(this).closest('form').validate().element($(this));
				});

         $('#mychosen').chosen().on('change', function(ev) {
					$(this).closest('form').validate().element($(this));
				});
         */
    };
    mainContent.on("pageshow.0301", function () {
        if (mainContent.find("[data-page=reply]").length > 0) {
            pageReady();
        }
    });
    $(document).on("click", "#st2_detail_risk", function () {
        var dialog = bootbox.dialog({
                title: "风险明细",
                size: "large",
                message: '<table id="detail-table"></table><div id="detail-pager"></div>',
                onEscape: function () {
                    $("#detail-table").jqGrid('GridDestroy', 'detail-table')
                },
                buttons: {
                    download: {
                        label: "下载",
                        className: "btn-info fa fa-download",
                        callback: function () {
                            var elemIF = document.createElement("iframe");
                            elemIF.src = $.router.server+"repm/detail_risk_download?fxid="+selectRow["fxid"]+"&cycle="+selectRow["hcsj"];
                            elemIF.style.display = "none";
                            document.body.appendChild(elemIF);
                            $(elemIF).ready(function(){
                                $(this).remove();
                            });
                            //$.ajax('http://192.168.1.113:8080/jhpt/anaydownload?id=&hcsj=2016-02&fxdj=&t=1455947187010', {
                            //    //data: form.find('textarea').serializeArray(),
                            //    dataType: 'json',
                            //    //files: form.find(':file'),
                            //    iframe: true,
                            //    processData: false
                            //}).always(function() {
                            //    //form.removeClass('loading');
                            //}).done(function(data) {
                            //    console.log(data); //form.find(':file').val('');
                            //});
                        }
                    },
                    success: {
                        label: "关闭",
                        className: "btn-success",
                        callback: function () {
                            $("#detail-table").jqGrid('GridDestroy', 'detail-table')
                        }
                    }
                }
            }
        ).init(function () {
            $('.modal-dialog').css({
                width:"80%"
            });
            $('.modal-body').css({
                overflow:"auto"
            });
            initDetailGrid();
        });
    });
})(jQuery);
